import socket
import re

def web_server(new_socket):

    request = new_socket.recv(4096).decode('utf-8')
    request_list = request.splitlines()
    print(request_list)
    if request_list:
        flie_name = ""
        ret = re.match(r"[^/]+(/[^ ]*)",request_list[0])
        if ret:
            flie_name = ret.group(1)
            if flie_name == "/":
                flie_name = "/index.html"
        try:
            flie = open('./html'+flie_name,"rb")

        except Exception as e:#如果没有就返回404
            response = "HTTP/1.1 404 Not Found\r\n"
            response += "\r\n"
            response += "-----cos------"
            new_socket.send(response.encode('utf-8'))
        else:
            html_centent = flie.read()
            flie.close()
            response = "HTTP/1.1 200 OK\r\n"
            response += "\r\n"
            #发送response head发送给浏览器
            new_socket.send(response.encode('utf-8'))
            #发送response boby给浏览器
            new_socket.send(html_centent)
    new_socket.close()

def main():
    """用来完成整体的控制"""
    # 1. 创建套接字
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    #为了确保端口复用
    tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # 2. 绑定
    tcp_server_socket.bind(("", 7890))

    # 3. 变为监听套接字
    tcp_server_socket.listen(128)

    while True:
        # 4. 等待新客户端的链接
        new_socket, client_addr = tcp_server_socket.accept()

        # 5. 为这个客户端服务
        web_server(new_socket)

    # 关闭监听套接字
    tcp_server_socket.close()

if __name__ == '__main__':
    main()